/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import daos.exceptions.PreexistingEntityException;
import daos.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entidades.Deportista;
import java.util.ArrayList;
import java.util.Collection;
import entidades.Evento;
import entidades.Competencia;
import entidades.Disciplina;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author usuario
 */
public class DisciplinaJpaController implements Serializable {

    public DisciplinaJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Disciplina disciplina) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (disciplina.getDeportistaCollection() == null) {
            disciplina.setDeportistaCollection(new ArrayList<Deportista>());
        }
        if (disciplina.getEventoCollection() == null) {
            disciplina.setEventoCollection(new ArrayList<Evento>());
        }
        if (disciplina.getCompetenciaCollection() == null) {
            disciplina.setCompetenciaCollection(new ArrayList<Competencia>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Deportista> attachedDeportistaCollection = new ArrayList<Deportista>();
            for (Deportista deportistaCollectionDeportistaToAttach : disciplina.getDeportistaCollection()) {
                deportistaCollectionDeportistaToAttach = em.getReference(deportistaCollectionDeportistaToAttach.getClass(), deportistaCollectionDeportistaToAttach.getCedula());
                attachedDeportistaCollection.add(deportistaCollectionDeportistaToAttach);
            }
            disciplina.setDeportistaCollection(attachedDeportistaCollection);
            Collection<Evento> attachedEventoCollection = new ArrayList<Evento>();
            for (Evento eventoCollectionEventoToAttach : disciplina.getEventoCollection()) {
                eventoCollectionEventoToAttach = em.getReference(eventoCollectionEventoToAttach.getClass(), eventoCollectionEventoToAttach.getIdEvento());
                attachedEventoCollection.add(eventoCollectionEventoToAttach);
            }
            disciplina.setEventoCollection(attachedEventoCollection);
            Collection<Competencia> attachedCompetenciaCollection = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionCompetenciaToAttach : disciplina.getCompetenciaCollection()) {
                competenciaCollectionCompetenciaToAttach = em.getReference(competenciaCollectionCompetenciaToAttach.getClass(), competenciaCollectionCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollection.add(competenciaCollectionCompetenciaToAttach);
            }
            disciplina.setCompetenciaCollection(attachedCompetenciaCollection);
            em.persist(disciplina);
            for (Deportista deportistaCollectionDeportista : disciplina.getDeportistaCollection()) {
                deportistaCollectionDeportista.getDisciplinaCollection().add(disciplina);
                deportistaCollectionDeportista = em.merge(deportistaCollectionDeportista);
            }
            for (Evento eventoCollectionEvento : disciplina.getEventoCollection()) {
                eventoCollectionEvento.getDisciplinaCollection().add(disciplina);
                eventoCollectionEvento = em.merge(eventoCollectionEvento);
            }
            for (Competencia competenciaCollectionCompetencia : disciplina.getCompetenciaCollection()) {
                Disciplina oldDisciplinaOfCompetenciaCollectionCompetencia = competenciaCollectionCompetencia.getDisciplina();
                competenciaCollectionCompetencia.setDisciplina(disciplina);
                competenciaCollectionCompetencia = em.merge(competenciaCollectionCompetencia);
                if (oldDisciplinaOfCompetenciaCollectionCompetencia != null) {
                    oldDisciplinaOfCompetenciaCollectionCompetencia.getCompetenciaCollection().remove(competenciaCollectionCompetencia);
                    oldDisciplinaOfCompetenciaCollectionCompetencia = em.merge(oldDisciplinaOfCompetenciaCollectionCompetencia);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findDisciplina(disciplina.getIdDisciplina()) != null) {
                throw new PreexistingEntityException("Disciplina " + disciplina + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Disciplina disciplina) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Disciplina persistentDisciplina = em.find(Disciplina.class, disciplina.getIdDisciplina());
            Collection<Deportista> deportistaCollectionOld = persistentDisciplina.getDeportistaCollection();
            Collection<Deportista> deportistaCollectionNew = disciplina.getDeportistaCollection();
            Collection<Evento> eventoCollectionOld = persistentDisciplina.getEventoCollection();
            Collection<Evento> eventoCollectionNew = disciplina.getEventoCollection();
            Collection<Competencia> competenciaCollectionOld = persistentDisciplina.getCompetenciaCollection();
            Collection<Competencia> competenciaCollectionNew = disciplina.getCompetenciaCollection();
            List<String> illegalOrphanMessages = null;
            for (Competencia competenciaCollectionOldCompetencia : competenciaCollectionOld) {
                if (!competenciaCollectionNew.contains(competenciaCollectionOldCompetencia)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Competencia " + competenciaCollectionOldCompetencia + " since its disciplina field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Deportista> attachedDeportistaCollectionNew = new ArrayList<Deportista>();
            for (Deportista deportistaCollectionNewDeportistaToAttach : deportistaCollectionNew) {
                deportistaCollectionNewDeportistaToAttach = em.getReference(deportistaCollectionNewDeportistaToAttach.getClass(), deportistaCollectionNewDeportistaToAttach.getCedula());
                attachedDeportistaCollectionNew.add(deportistaCollectionNewDeportistaToAttach);
            }
            deportistaCollectionNew = attachedDeportistaCollectionNew;
            disciplina.setDeportistaCollection(deportistaCollectionNew);
            Collection<Evento> attachedEventoCollectionNew = new ArrayList<Evento>();
            for (Evento eventoCollectionNewEventoToAttach : eventoCollectionNew) {
                eventoCollectionNewEventoToAttach = em.getReference(eventoCollectionNewEventoToAttach.getClass(), eventoCollectionNewEventoToAttach.getIdEvento());
                attachedEventoCollectionNew.add(eventoCollectionNewEventoToAttach);
            }
            eventoCollectionNew = attachedEventoCollectionNew;
            disciplina.setEventoCollection(eventoCollectionNew);
            Collection<Competencia> attachedCompetenciaCollectionNew = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionNewCompetenciaToAttach : competenciaCollectionNew) {
                competenciaCollectionNewCompetenciaToAttach = em.getReference(competenciaCollectionNewCompetenciaToAttach.getClass(), competenciaCollectionNewCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollectionNew.add(competenciaCollectionNewCompetenciaToAttach);
            }
            competenciaCollectionNew = attachedCompetenciaCollectionNew;
            disciplina.setCompetenciaCollection(competenciaCollectionNew);
            disciplina = em.merge(disciplina);
            for (Deportista deportistaCollectionOldDeportista : deportistaCollectionOld) {
                if (!deportistaCollectionNew.contains(deportistaCollectionOldDeportista)) {
                    deportistaCollectionOldDeportista.getDisciplinaCollection().remove(disciplina);
                    deportistaCollectionOldDeportista = em.merge(deportistaCollectionOldDeportista);
                }
            }
            for (Deportista deportistaCollectionNewDeportista : deportistaCollectionNew) {
                if (!deportistaCollectionOld.contains(deportistaCollectionNewDeportista)) {
                    deportistaCollectionNewDeportista.getDisciplinaCollection().add(disciplina);
                    deportistaCollectionNewDeportista = em.merge(deportistaCollectionNewDeportista);
                }
            }
            for (Evento eventoCollectionOldEvento : eventoCollectionOld) {
                if (!eventoCollectionNew.contains(eventoCollectionOldEvento)) {
                    eventoCollectionOldEvento.getDisciplinaCollection().remove(disciplina);
                    eventoCollectionOldEvento = em.merge(eventoCollectionOldEvento);
                }
            }
            for (Evento eventoCollectionNewEvento : eventoCollectionNew) {
                if (!eventoCollectionOld.contains(eventoCollectionNewEvento)) {
                    eventoCollectionNewEvento.getDisciplinaCollection().add(disciplina);
                    eventoCollectionNewEvento = em.merge(eventoCollectionNewEvento);
                }
            }
            for (Competencia competenciaCollectionNewCompetencia : competenciaCollectionNew) {
                if (!competenciaCollectionOld.contains(competenciaCollectionNewCompetencia)) {
                    Disciplina oldDisciplinaOfCompetenciaCollectionNewCompetencia = competenciaCollectionNewCompetencia.getDisciplina();
                    competenciaCollectionNewCompetencia.setDisciplina(disciplina);
                    competenciaCollectionNewCompetencia = em.merge(competenciaCollectionNewCompetencia);
                    if (oldDisciplinaOfCompetenciaCollectionNewCompetencia != null && !oldDisciplinaOfCompetenciaCollectionNewCompetencia.equals(disciplina)) {
                        oldDisciplinaOfCompetenciaCollectionNewCompetencia.getCompetenciaCollection().remove(competenciaCollectionNewCompetencia);
                        oldDisciplinaOfCompetenciaCollectionNewCompetencia = em.merge(oldDisciplinaOfCompetenciaCollectionNewCompetencia);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = disciplina.getIdDisciplina();
                if (findDisciplina(id) == null) {
                    throw new NonexistentEntityException("The disciplina with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Disciplina disciplina;
            try {
                disciplina = em.getReference(Disciplina.class, id);
                disciplina.getIdDisciplina();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The disciplina with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Competencia> competenciaCollectionOrphanCheck = disciplina.getCompetenciaCollection();
            for (Competencia competenciaCollectionOrphanCheckCompetencia : competenciaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Disciplina (" + disciplina + ") cannot be destroyed since the Competencia " + competenciaCollectionOrphanCheckCompetencia + " in its competenciaCollection field has a non-nullable disciplina field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Deportista> deportistaCollection = disciplina.getDeportistaCollection();
            for (Deportista deportistaCollectionDeportista : deportistaCollection) {
                deportistaCollectionDeportista.getDisciplinaCollection().remove(disciplina);
                deportistaCollectionDeportista = em.merge(deportistaCollectionDeportista);
            }
            Collection<Evento> eventoCollection = disciplina.getEventoCollection();
            for (Evento eventoCollectionEvento : eventoCollection) {
                eventoCollectionEvento.getDisciplinaCollection().remove(disciplina);
                eventoCollectionEvento = em.merge(eventoCollectionEvento);
            }
            em.remove(disciplina);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Disciplina> findDisciplinaEntities() {
        return findDisciplinaEntities(true, -1, -1);
    }

    public List<Disciplina> findDisciplinaEntities(int maxResults, int firstResult) {
        return findDisciplinaEntities(false, maxResults, firstResult);
    }

    private List<Disciplina> findDisciplinaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Disciplina.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Disciplina findDisciplina(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Disciplina.class, id);
        } finally {
            em.close();
        }
    }

    public int getDisciplinaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Disciplina> rt = cq.from(Disciplina.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
